<template>
  <div class="app-container">
    <!--搜索-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入姓名"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-select
          v-model="queryParams.className"
          placeholder="班级"
          clearable
          size="small"
          style="width: 180px">
          <el-option
            v-for="item in classOptions"
            :key="item.id"
            :label="item.className"
            :value="item.className"
          >
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="请假类型" prop="leaveType">
        <el-select
          v-model="queryParams.leaveType"
          placeholder="请假类型"
          clearable
          size="small"
          style="width: 180px">
          <el-option
            v-for="dict in leaveTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请假状态"
          clearable
          size="small"
          style="width: 180px">
          <el-option
           v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="请假日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--表格操作栏-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['smartdor:sdleave:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['smartdor:sdleave:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['smartdor:sdleave:remove']"
        >删除</el-button>
      </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col> -->
    </el-row>

    <!--表格主体-->
    <el-table v-loading="loading" :data="sdleaveList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="60"  />
      <el-table-column label="学号" align="center" prop="studentNo"  />
      <el-table-column label="班级" align="center" prop="className"  />
      <el-table-column label="学生姓名" align="center" prop="studentName"  />
      <!-- <el-table-column label="学生手机号" align="center" prop="studentPhone"  /> -->
      <el-table-column label="请假类型" align="center" prop="leaveType" :formatter="leaveTypeFormat" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="100"/>
      <el-table-column label="结束日期" align="center" prop="endDate" width="100"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240px">
        <template slot-scope="scope" >
          <el-button
                  size="mini"
                  circle type="info"
                  icon="el-icon-view"
                  @click="handleView(scope.row,scope.index)"
                  v-hasPermi="['smartdor:sdleave:query']"
          />
          <el-button
                  size="mini"
                  circle type="success"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['smartdor:sdleave:edit']"
          />
          <el-button v-if="scope.row.status==='2'"
                  @click="handleApproval(scope.row)"
                  v-hasPermi="['smartdor:sdleave:approval']"
                  style="background-color: #00aa00; color: white;width:60px;"
          >审核</el-button>
          <el-button v-if="scope.row.status==='2'"
                   @click="handleReject(scope.row)"
                   v-hasPermi="['smartdor:sdleave:reject']"
                   style="background-color: #ff5500; color: white;width:60px;"
           >驳回</el-button>
           <el-button
                   size="mini"
                   circle type="danger"
                   icon="el-icon-delete"
                   @click="handleDelete(scope.row)"
                   v-hasPermi="['smartdor:sdleave:remove']"
           />

        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 请假详细 -->
    <el-dialog title="请假详情" :visible.sync="open1" width="700px">
      <el-form ref="form" :model="form" label-width="140px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学号："> {{ form.studentNo }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级："> {{ form.className }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学生姓名："> {{ form.studentName }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学生手机号："> {{ form.studentPhone }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假类型：">{{ leaveTypeFormat(form) }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假日期："> {{ form.startDate }} 至 {{ form.endDate }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：">{{ statusFormat(form) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请假原因：">{{form.leaveReason}}</el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="家长描述信息：">{{form.parentDesc}}</el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="班主任描述信息：">{{form.teacherDesc}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假记录提交时间:"> {{form.createTime}}</el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open1 = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title2" :visible.sync="open2" width="650px">
      <el-form ref="form1" :model="form" :rules="rules1" label-width="120px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
           <el-form-item label="班级" >
           <el-select  v-model="form.classId" placeholder="请选择" :disabled="disabledInput" clearable @change="change1">
              <el-option
                v-for="item in classOptions"
                :key="item.id"
                :label="item.className"
                :value="item.id">
              </el-option>
            </el-select>
           </el-form-item>
           </el-col>

           <el-col :span="12">
            <el-form-item label="学生姓名" >
            <el-select  v-model="form.studentNo" placeholder="请选择" :disabled="disabledInput" clearable>
               <el-option
                 v-for="item1 in studentOptions"
                 :key="item1.studentNo"
                 :label="item1.studentName"
                 :value="item1.studentNo">
               </el-option>
             </el-select>
            </el-form-item>
            </el-col>

          <!-- <el-col :span="12">
             <el-form-item label="学生姓名" prop="studentName" >
                 <el-input v-model="form.studentName" :disabled="disabledInput"></el-input>
             </el-form-item>
           </el-col> -->

       <!-- <el-col :span="12">
         <el-form-item label="学号" prop="studentNo" >
           <el-input v-model="form.studentNo" :disabled="disabledInput"></el-input>
         </el-form-item>
        </el-col> -->
        <el-col :span="12">
            <el-form-item label="请假类型" prop="leaveType">
                <el-select v-model="form.leaveType" placeholder="请选择请假类型">
                  <el-option
                      v-for="item in leaveTypeOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue">
                  </el-option>
                </el-select>
            </el-form-item>
        </el-col>

    <el-col :span="24">
       <!-- <el-form-item label="请假日期" prop="leaveDate">
           <div class="block">
             <el-date-picker
                 v-model="form.leaveDate"
                 type="date"
                 placeholder="请选择请假日期"
                 value-format="yyyy-MM-dd"
                 >
             </el-date-picker>
           </div>
       </el-form-item> -->

       <el-form-item label="请假日期" prop="startDate">
         <el-date-picker
                 v-model="form.startDate"
                 type="date"
                 :picker-options="pickerOptionsStart"
                 size="small"
                 style="width: 140px"
                 format="yyyy-MM-dd"
                 value-format="yyyy-MM-dd HH:mm:ss"
                 start-placeholder="开始日期"
         />
       </el-form-item>
       <!-- </el-col> -->
       <!-- <el-col :span="12"> -->
       <el-form-item label="至" prop="endDate">
         <el-date-picker :picker-options="pickerOptionsEnd"
                 v-model="form.endDate"
                 type="date"
                 size="small"
                 style="width: 140px"
                 format="yyyy-MM-dd"
                 value-format="yyyy-MM-dd HH:mm:ss"
                 end-placeholder="结束日期"
         />
       </el-form-item>

     </el-col>

     <el-col :span="24">
       <el-form-item label="请假原因" prop="leaveReason">
           <el-input type="textarea" v-model="form.leaveReason"></el-input>
       </el-form-item>
        </el-col>
   <el-col :span="24">
       <el-form-item label="班主任描述信息" prop="teacherDesc">
           <el-input type="textarea" v-model="form.teacherDesc"></el-input>
       </el-form-item>
     </el-col>
   </el-row>
      </el-form>
     <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 驳回对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="10" class="mb8">


       <el-col :span="24">
        <el-form-item label="驳回描述信息" prop="teacherDesc">
          <el-input type="textarea"  v-model="form.teacherDesc" placeholder="请输入驳回描述信息" />
        </el-form-item>
       </el-col>

     </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  学生请假信息导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open3" width="400px">
        <el-upload
          ref="upload"
          :limit="1"
          multiple="multiple"
          name="upload"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"/>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
          </div>
          <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open3 = false">取 消</el-button>
        </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSdLeave, getSdLeave,addSdLeave,updateSdLeave,exportSdLeave,approveStatus,reject,importTemplate,delSdLeave} from "@/api/smartdor/sdleave";
import { getStuInfoByClassId } from '@/api/basedata/bstudent'
import { listAllBClass } from "@/api/basedata/bclass";
import { getToken } from '@/utils/auth'

export default {
  name: "SdLeave",
  data() {
    return {
      // 搜索-日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentNo: undefined,
        studentName: undefined,
        className: undefined,
        leaveType: undefined,
        status: undefined,
        startDate: undefined,
        endDate: undefined
      },
      //表格数据
      sdleaveList: [],
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      //请假类型下拉
      leaveTypeOptions: [],
      //审批状态下拉
      statusOptions: [],
      //班级信息下拉
      classOptions: [],
      //学生信息下拉
      studentOptions: [],
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      title2: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      disabledInput:false,
      createTime: new Date().getTime(),
      pickerOptionsStart:{
          disabledDate:(time)=> {
            if (this.form.endDate) {
              return time.getTime() > new Date(this.form.endDate).getTime() || time.getTime() <= new Date(this.createTime).getTime();
            }
            return time.getTime() <= new Date(this.createTime).getTime() - 86400000;
          }
      },
      pickerOptionsEnd:{
          disabledDate:(time)=> {
            if (this.form.startDate) {
              return time.getTime() < new Date(this.form.startDate).getTime();
            }
            return time.getTime() <= new Date(this.createTime).getTime() - 86400000;
          }
      },
      //请假导入参数
      upload: {
        // 是否显示弹出层（请假导入）
        open3: false,
        // 弹出层标题（请假导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的请假数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: "http://localhost:9003/smartdor/sdleave/importData",
        url: process.env.VUE_APP_BASE_API + "/smartdor/sdleave/importData",
      },
      // 表单参数
      form: {},
      // 表单参数
      form1: {},
      // 表单校验
      rules: {
        teacherDesc: [
          { required: true, message: "驳回描述信息不能为空", trigger: "blur" }
        ],
      },
      rules1: {
        studentName: [
          { required: true, message: "学员姓名不能为空", trigger: "blur" }
        ],
        studentNo: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "请假开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "请假结束日期不能为空", trigger: "blur" }
        ],
        leaveReason: [
          { required: true, message: "请假原因不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.setDateRangeForNextWeek(); //设置日期默认为一周内
    this.getList(); //列表
    this.listAllBClass(); //班级下拉
    this.getDicts("leave_status").then(response => {
      this.statusOptions = response.data;
    }); //审批状态
    this.getDicts("leave_type").then(response => {
      this.leaveTypeOptions = response.data;
    }); //请假类型
  },
  methods: {
    /**搜索日期默认显示一周内 */
    setDateRangeForNextWeek() {  
      const today = new Date();  
      const startDay = new Date(today);  
      const endDay = new Date(today);  
      // 设置开始日期为本周一（如果今天不是周一，则找到本周一）  
      startDay.setDate(startDay.getDate() - startDay.getDay() + 1);  
      // 设置结束日期为本周日  
      endDay.setDate(endDay.getDate() - endDay.getDay() + 7);  
      // 转换为所需的日期格式  
      this.dateRange[0] = this.formatDate(startDay);  
      this.dateRange[1] = this.formatDate(endDay);  
    },  
    formatDate(date) {  
      return date.getFullYear() + '-' +  
        ('0' + (date.getMonth() + 1)).slice(-2) + '-' +  
        ('0' + date.getDate()).slice(-2);  
    },  
    /** 查询请假列表 */
    getList() {
      this.loading = true;
      this.queryParams.startDate = this.dateRange[0];
      this.queryParams.endDate = this.dateRange[1];
  
      listSdLeave(this.queryParams).then(response => {
        this.sdleaveList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });

    },
    /**加载班级信息 */
    listAllBClass(){
      listAllBClass().then(response => {
        this.classOptions = response.data;
      });
    },
    // 字典设备状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    leaveTypeFormat(row, column) {
      return this.selectDictLabel(this.leaveTypeOptions, row.leaveType);
    },
    change1(){
      this.studentOptions=[];

    	 // 获取班级ID
    	let classId_dictValue=this.classOptions.find(val=>val.id==this.form.classId).id

    	getStuInfoByClassId(classId_dictValue).then(response => {
    	     this.studentOptions = response.data;
           console.log(this.studentOptions);
    	   }
    	 );

    },
    // 审核通过
    handleApproval(row) {
      row.status ="3";
      this.$confirm('确定审核通过？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return approveStatus(row.id, row.status);
        }).then(() => {
          this.msgSuccess("审核通过!!!");
        }).catch(function() {
          this.msgSuccess("异常!!!");
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form1 = {
        id: undefined,
        studentNo: undefined,
        classId: undefined,
        studentName: undefined,
        leaveType: undefined,
        leaveDate: undefined,
        leaveReason: undefined,
        status: "3",
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open2 = true;
      this.title2 = "添加请假信息";
      this.disabledInput=false;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSdLeave(id).then(response => {
        this.form = response.data;
        this.open2 = true;
        this.title2 = "修改请假信息";
        this.disabledInput=true;
      });
    },
    /** 驳回按钮操作 */
    handleReject(row) {
      this.reset();
      const id = row.id || this.ids
      getSdLeave(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "驳回请假信息";
      });
    },
    /** 提交按钮 */
    submitForm1: function() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateSdLeave(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open2 = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {
            addSdLeave(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open2 = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            this.form.status="5";
            reject(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("驳回成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {

          }
        }
      });
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open1 = true;
      this.form = row;
    },
    // 导入按钮操作
    handleImport() {
      this.upload.title = "请假导入";
      this.upload.open3 = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open3 = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.message, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 下载模板操作
    importTemplate() {
      importTemplate().then(response => {
        this.fileDownload(response.data, "请假管理模板.xlsx");
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除请假序号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSdLeave(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm('是否确认导出所有短信模板数据项?', "警告", {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning"
    //     }).then(function() {
    //       return exportSmsTemplate(queryParams);
    //     }).then(response => {
    //       this.download(response.msg);
    //     }).catch(function() {});
    // },

  }
};
</script>
